package com.wangsd.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;

import java.io.File;
import java.io.InputStream;

public class OssFileUtils {
    //oss的访问域名
    private static final String endpoint = "http://oss-cn-beijing.aliyuncs.com";
    //账号
    private static final String accessKeyId = "LTAI5tDStQhDQ7xUTv4L5oYK";
    //密码
    private static final String accessKeySecret = "E1bJuwgMLReBQANZmuW0fYczrOS8Oy";
    //存储空间名称
    private static final String bucketName = "qianhuyun003";
    //访问路径
    private  static final String imgUrl = "https://qianhuyun003.oss-cn-beijing.aliyuncs.com";

    private static void upload(PutObjectRequest putObjectRequest) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setHeader("x-oss-forbid-overwrite", true);
        putObjectRequest.setMetadata(metadata);
        ossClient.putObject(putObjectRequest);
        ossClient.shutdown();
    }
    public static String uploadFile(String filename, File file, String baseName) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, baseName + filename, file);
        upload(putObjectRequest);
        return imgUrl + "/" + baseName + filename;
    }

    public static String uploadFile(String filename, InputStream inputStream, String baseName) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, baseName + filename, inputStream);
        upload(putObjectRequest);
        return imgUrl + "/" + baseName + filename;
    }

    public static void deleteFile(String filename, String baseName) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.deleteObject(bucketName, baseName + filename);
        ossClient.shutdown();
    }

    public static void main(String[] args) {
        String filename = "aaa.png";
        File file = new File("C:\\Users\\Administrator.8L21NRYQRM7LVAW\\Desktop\\aaa.png");
//        String str = new OssFileUtils().uploadFile(filename, file);
        new OssFileUtils().deleteFile("20200208232004805.png", "image/");
    }
}
